<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\AmazonPlanStatus;
use App\Models\AmazonSkulist;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SavePdfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params)
    {
        //
        $this->params = $params;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        echo '队列SavePdfJob';
        // var_dump($this->params);
        try {
            //消化队列
            // $data = $this->params;
            // if($data['type']==1){
            //     $this->save_pdf($this->params);
            // }else{
            //     $this->save_pdfb($this->params);
            // }
            $this->save_pdf($this->params);
            $this->save_pdfb($this->params);

        } catch(\Exception $e){

            //消化失败，记录错误日志
            // var_dump($e);
            $errmsg = $e->getMessage().'line:'.$e->getLine();
            // $errmsg = json_encode($e);
                $add['job'] = 'new_product_export';
                $add['time'] = time();
                $add['msg'] =  $errmsg;
                $add['data'] = json_encode($this->params);
                Db::table('job_err_log')->insert($add);
        }
    }


    public function save_pdf($params)
    {



        $DigitalModel = new \App\Models\DigitalModel();
        $plan_id = $params['plan_id'];
        $result = $DigitalModel->GetPdfNew($params);
        // var_dump( $result);
        $file = public_path() . DIRECTORY_SEPARATOR . 'pdf' . DIRECTORY_SEPARATOR . 'fba发货计划' . $plan_id . '.pdf';
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'tcpdf' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'tcpdf_include.php');
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setCreator(PDF_CREATOR);
        $pdf->setAuthor('Nicola Asuni');
        $pdf->setTitle('TCPDF Example 048');
        $pdf->setSubject('TCPDF Tutorial');
        $pdf->setKeywords('TCPDF, PDF, example, test, guide');
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->setHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->setFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
            require_once(dirname(__FILE__) . '/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        $pdf->AddPage();
        $pdf->setFont('stsongstdlight', '', 12);
        $pdf->setLeftMargin(3);

        $plan_res = json_decode(json_encode($result['plan_res']),true);
        $shop_name =  $plan_res['shop_name'];
        $transport =  $plan_res['transportation_mode_name']??'';
        $account =  $plan_res['account'];
        $box_code =  $plan_res['box_code'];
        // $delivery_date = $result['delivery_date'];
        // $courier_date = $result['courier_date'];
        // $shipping_date = $result['shipping_date'];
        // $air_date = $result['air_date'];


        $tbl = "
<table cellspacing= \"0\" cellpadding=\"1\" border=\"1\">
    <tr>
        <td> 店铺名</td>
        <td> $shop_name</td>
    </tr>
    <tr>
     <td> 运输类别</td>
     <td> $transport</td>
    </tr>
    <tr>
     <td> 发货计划id</td>
     <td> $plan_id</td>
    </tr>
    <tr style=\"color:red;\">
     <td> 仓库任务号</td>
     <td> $box_code</td>
    </tr>
    <tr>
    <td> 发货计划人</td>
    <td> $account</td>
   </tr>";

//     if(count($result['zuhe'])>0){
//         foreach ($result['zuhe'] as $zk => $zv) {
//             # code...
//         $tbl .= <<<EOD
// <tr>
// <td> 多件套-$zk</td>
// <td> $zv</td>
// </tr>
// EOD;
//     }
//     }
$tbl .= "</table>";
  

//         $tbl .= <<<EOD
// </table>
// EOD;
        // var_dump($tbl);
        try {
            //code...
            $pdf->writeHTML($tbl, true, false, false, false, '');
        } catch (\Throwable $e) {
            //throw $th;
            var_dump( $e->getMessage().'line:'.$e->getLine());
        }
        // $pdf->writeHTML($tbl, true, false, false, false, '');
        // echo 1;
        $pdf->Write(0, '补货单明细', '', 0, 'L', true, 0, false, false, 0);
        $pdf->setFont('stsongstdlight', '', 10);
        // echo 2;
        $tbl2 = <<<EOD
<table cellspacing="0" cellpadding="1" border="1">
<tr>
<td width="60">库位</td>
<td width="80">批次</td>
<td width="40">图片</td>
<td width="120"> 库存sku</td>
<td width="120"> 中文名</td>
<td width="80"> fnsku</td>
<td width="30">补货数量</td>
EOD;
            $tbl2 .= <<<EOD
</tr>
EOD;
// echo 3;
$locode = [];
foreach ($result['data'] as $item) {        

    if(in_array($item->location_code,$locode)){
        $locating_code = '';
    }else{
        $locating_code = $item->location_code;
        $locode[] =  $item->location_code;
    }
            $tbl2 .= <<<EOD
<tr>
<td style="color:red;"> $locating_code</td>
<td> $item->no</td>
<td> <img height="30" src="{$item->img}"></td>
<td> $item->custom_sku</td>
<td> $item->name_cn</td>
<td> $item->fnsku</td>
<td> $item->box_num </td>
EOD;
$tbl2 .= <<<EOD
</tr>
EOD;
}
// echo 4;

        $tbl2 .= <<<EOD
</table>
EOD;

    // var_dump($tbl);
    // var_dump($tbl2);

    try {
        //code...
        $pdf->writeHTML($tbl2, true, false, false, false, 'left');
    } catch (\Throwable $e) {
        //throw $th;
        var_dump( $e->getMessage().'line:'.$e->getLine());
    }
       

        $pdf->Output($file, 'F');
        $url = "/pdf/fba发货计划" . $plan_id . '.pdf';
        $add['plan_id'] = $plan_id;
        $add['create_time'] = date('Y-m-d H:i:s');
        $add['path'] =  $url;
        $add['user_id'] =  $params['user_info']['user_id'];
        $add['request_status'] =  $params['request_status'];
        $add['type'] = 1;
        Db::table('save_pdf_log')->insert($add);


    }




    
    public function save_pdfb($params)
    {

        $DigitalModel = new \App\Models\DigitalModel();
        $plan_id = $params['plan_id'];
        $result = $DigitalModel->buhuoPlan_data($params);
        // var_dump( $result);
        $file = public_path() . DIRECTORY_SEPARATOR . 'pdf' . DIRECTORY_SEPARATOR . 'fba发货计划_n' . $plan_id . '.pdf';
        require_once(app_path() . DIRECTORY_SEPARATOR . 'Libs' . DIRECTORY_SEPARATOR . 'tcpdf' . DIRECTORY_SEPARATOR . 'examples' . DIRECTORY_SEPARATOR . 'tcpdf_include.php');
        // create new PDF document
        $pdf = new \TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setCreator(PDF_CREATOR);
        $pdf->setAuthor('Nicola Asuni');
        $pdf->setTitle('TCPDF Example 048');
        $pdf->setSubject('TCPDF Tutorial');
        $pdf->setKeywords('TCPDF, PDF, example, test, guide');
        $pdf->setFooterFont(array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
        $pdf->setDefaultMonospacedFont(PDF_FONT_MONOSPACED);
        $pdf->setMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->setHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->setFooterMargin(PDF_MARGIN_FOOTER);
        $pdf->setAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
            require_once(dirname(__FILE__) . '/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        $pdf->AddPage();
        $pdf->setFont('stsongstdlight', '', 12);
        $pdf->setLeftMargin(3);


        $shop_name = $result['shop_name'];
        $sum = $result['sum'];
        $transport = $result['transport'];
        $account = $result['account'];
        // $delivery_date = $result['delivery_date'];
        // $courier_date = $result['courier_date'];
        // $shipping_date = $result['shipping_date'];
        // $air_date = $result['air_date'];



        $tbl = "
<table cellspacing= \"0\" cellpadding=\"1\" border=\"1\">
    <tr>
        <td> 店铺名</td>
        <td> $shop_name</td>
    </tr>
    <tr>
     <td> 运输类别</td>
     <td> $transport</td>
    </tr>
    <tr>
     <td> 发货计划id</td>
     <td> $plan_id</td>
    </tr>
    <tr>
    <td> 发货计划人</td>
    <td> $account</td>
   </tr>";

        if ($result['desc']!='') {
            $tbl = $tbl . "
    <tr>
     <td> 备注</td>
     <td> {$result['desc']}</td>
    </tr>
    </table>";
        } else {
            $tbl .= "</table>";
        }

        $pdf->writeHTML($tbl, true, false, false, false, '');
        $pdf->Write(0, '补货单明细', '', 0, 'L', true, 0, false, false, 0);
        $pdf->setFont('stsongstdlight', '', 10);
        $tbl2 = <<<EOD
<table cellspacing="0" cellpadding="1" border="1">
<tr>
<td width="150"> SKU</td>
<td width="40">图片</td>
<td width="100"> 库存sku</td>
<td width="120"> 中文名</td>
<td width="40"> fnsku</td>
EOD;
        // $courier_sum = array_sum(array_column($result['data'], 'courier_num'));
        // $shipping_sum = array_sum(array_column($result['data'], 'shipping_num'));
        // $air_sum = array_sum(array_column($result['data'], 'air_num'));
        // $num_sum = array_sum(array_column($result['data'], 'num_sum'));
        // $string = '';
        // if ($courier_sum > 0) {
        //     $string = "补货数量（快递)";
        // } elseif ($shipping_sum > 0) {
        //     $string = "补货数量（海运)";
        // } elseif ($air_sum > 0) {
        //     $string = "补货数量（空运）";
        // }
        $string = "补货数量";
        $tbl2 .= <<<EOD
<td width="30">$string</td>

</tr>
EOD;

        // $zuhe_data = $result['zuhe_data'];


        foreach ($result['data'] as $item) {            
            $product_cn = $item->product_name??'';
            // $self_delivery_inventory = $item->self_delivery_inventory;
            // $tongAn_inventory = $item->tongAn_inventory;
            // $quanzhou_inventory =  $item->quanzhou_inventory;
            $rowSku = $item->sku??'';
            $customSku = $item->custom_sku??'';
            $transport_num = 0;
            $img = $item->img??'';
            
            $transport_num = $item->num_sum??0;
           
            // if ($item->courier_num > 0) {
            //     $transport_num = $item->courier_num;
            // } elseif ($item->shipping_num > 0) {
            //     $transport_num = $item->shipping_num;
            // } elseif ($item->air_num > 0) {
            //     $transport_num = $item->air_num;
            // }
            $fnsku = $item->fnsku??'';
            $tbl2 .= <<<EOD
<tr>
<td> $rowSku</td>
<td> <img height="30" src="{$img}"></td>
<td> $customSku</td>
<td> $product_cn</td>
<td> $fnsku</td>
<td> $transport_num </td>
</tr>
EOD;



// var_dump($zuhe_data);
            // echo 1;
//             if($item->type==2){
        
//                 foreach ($zuhe_data as $zk => $zv) {

//                     if($zk==$customSku){
//                         // var_dump($zv);
//                         $i = 1;
//                         if(count($zv)>=1){
//                         foreach ($zv as $zvv) {
//                             # code...
//                             $product_cn = $zvv['product_name']??'';
//                             $self_delivery_inventory = $zvv['self_delivery_inventory']??0;
//                             $tongAn_inventory = $zvv['tongAn_inventory']??0;
//                             $rowSku = $item->sku.'子成员'.$i;
//                             $customSku = $zvv['custom_sku']??'';
//                             $quanzhou_inventory =  $zvv['quanzhou_inventory']??0;
//                             $transport_num = 0;
//                             $img = $zvv['img']??'';  
//                             $transport_num = '';
//                             $fnsku = '';

//                             $tbl2 .= <<<EOD
// <tr>
// <td  style="color:red;"> $rowSku</td>
// <td> <img height="30" src="{$img}"></td>
// <td  style="color:red;"> $customSku</td>
// <td  style="color:red;"> $product_cn</td>
// <td> $fnsku</td>
// <td> $transport_num</td>
// </tr>
// EOD;
//                             $i++;
//                         }
//                         }

//                     }
//                 }

//                 // echo 2;
                
//             }

        }

        $tbl2 .= <<<EOD
</table>
EOD;



        try {
            //code...
            $pdf->writeHTML($tbl2, true, false, false, false, 'left');
            $pdf->Output($file, 'F');
        } catch (\Throwable $th) {
            //throw $th;
            var_dump($tbl2);
            var_dump($th->getMessage());
        }
       


        $url = "/pdf/fba发货计划_n" . $plan_id . '.pdf';
        $add['plan_id'] = $plan_id;
        $add['create_time'] = date('Y-m-d H:i:s');
        $add['path'] =  $url;
        $add['user_id'] =  $params['user_info']['user_id'];
        $add['request_status'] =  $params['request_status'];
        $add['type'] = 2;
        Db::table('save_pdf_log')->insert($add);


    }




    // public function powers($data){
	// 	$identity = "'".implode("','", $data['identity'])."'";
	// 	$sql = "select pr.*
	// 			       from xt_role_user_join ruj
	// 			       left join (select prj.role_id, prj.power_id, p.*
	// 			                         from xt_powers_role_join prj
	// 			                         inner join xt_powers p on p.Id=prj.power_id
	// 			                  ) as pr on pr.role_id = ruj.role_id
	// 			       where ruj.user_id={$data['user_id']} and pr.identity in ({$identity})
	// 			       group by pr.power_id";
	// 	$power_list = json_decode(json_encode(db::select($sql)), true);
		
	// 	$array = array();
	// 	foreach ($power_list as $k=>$v){
	// 		$array[] = $v['identity'];
	// 	}
		
	// 	$powers = array();
	// 	foreach ($data['identity'] as $va){
	// 		if(in_array($va, $array)){
	// 			$powers[$va] = true;
	// 		}else{
	// 			$powers[$va] = false;
	// 		}
	// 	}
	// 	return $powers;
		
	// }
}
